﻿module HostTracker.Azure.Management.FSharpExtensions

open HostTracker.Azure.ProjectSettings
open System
open Microsoft.FSharp.Reflection

type ServiceConfiguration with
    member x.RolesAsMap = 
        [for role in x.Roles -> role.Name, role] |> Map.ofList    
    member x.SetInstanceCountFor roleName count =
        match Map.tryFind roleName x.RolesAsMap with
        | None -> ()
        | Some role -> role.InstanceConfig.Count <- count

type System.String with 
    member x.ToBase64() =
        if (String.IsNullOrEmpty(x)) then ""
        else System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(x))
    member x.FromBase64() =
        if (String.IsNullOrEmpty(x)) then ""
        else System.Text.Encoding.UTF8.GetString(System.Convert.FromBase64String(x))

module Reflection =
    let unionToString (unionType: Type) (nameMapper: string -> string) = 
        fun x -> (FSharpValue.GetUnionFields (x,unionType) |> fst).Name |> nameMapper
    let stringToUnion (unionType: Type) nameMapper (str: string) =
        let unionCaseInfo = FSharpType.GetUnionCases unionType |> Array.find (fun case -> (nameMapper case.Name) = str)
        FSharpValue.MakeUnion (unionCaseInfo, [||])
    let unionToStringPlain<'a> (inst:'a) = unionToString typeof<'a> (fun x -> x) inst
    let stringToUnionPlain<'a> (str: string) = stringToUnion typeof<'a> (fun x -> x) str :?> 'a